package com.zhaojonhy.zhaopangwb.ui;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.StatusesAPI;
import com.sina.weibo.sdk.openapi.UsersAPI;
import com.zhaojonhy.zhaopangwb.Fragment.HomeFragment;
import com.zhaojonhy.zhaopangwb.R;
import com.zhaojonhy.zhaopangwb.adapter.StatusAdapter;
import com.zhaojonhy.zhaopangwb.bean.Statuses;
import com.zhaojonhy.zhaopangwb.bean.StatusesFriendsTimeline;
import com.zhaojonhy.zhaopangwb.bean.User;
import com.zhaojonhy.zhaopangwb.utils.AccessTokenKeeper;
import com.zhaojonhy.zhaopangwb.utils.BaseApplication;
import com.zhaojonhy.zhaopangwb.utils.Constants;
import com.zhaojonhy.zhaopangwb.utils.TitleBuilder;
import com.zhaojonhy.zhaopangwb.widget.Pull2RefreshListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/10/24.
 */

public class SelfStatuseActivity extends Activity implements View.OnClickListener{

    private static final String TAG = SelfStatuseActivity.class.getName();

    //标题栏
    private View title ;
    private TextView titleBarTv ;
    /** 当前 Token 信息 */
    private Oauth2AccessToken mAccessToken;
    /** 用于获取微博信息流等操作的API */
    private StatusesAPI statusesAPI;

    // 用户相关信息
    private boolean isCurrentUser;
    private User user;
    private String userName ;
    private BaseApplication application ;
    // 个人微博列表
    private List<Statuses> statuses = new ArrayList<Statuses>();
    private StatusAdapter statusAdapter;
    // 刷新列表
    private Pull2RefreshListView plv_user_info;
    private View footView ;
    //显示当前已加载至的页数
    private int curPage = 1 ;

    //判断是否为@我的微博
    private boolean isAtWeibo = false ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_self_statuse);

        mAccessToken = AccessTokenKeeper.readAccessToken(this) ;
        statusesAPI = new StatusesAPI(this, Constants.APP_KEY, mAccessToken) ;

        isAtWeibo = getIntent().getBooleanExtra("isAtWeibo",false) ;
        Log.d(TAG,"isAtWeibo :" + isAtWeibo );

        application = (BaseApplication) getApplication();
        user = application.currentUser ;
        Log.d(TAG,"user'id:"+user.getId()) ;
        Log.d(TAG,"user'name:"+user.getName()) ;
        initView();
    }

    private void initView() {
        //title 标题栏
        initTitle();
//        //listView headView 微博信息
//        initDetailHead();
//
        //listView 下拉刷新控件
        initListView();
        // 加载用户所属微博列表
        loadStatuses(1) ;
    }
    private void initTitle() {
        title = new TitleBuilder(this)
                .setTitleBgRes(R.drawable.navigationbar_background)
                .setLeftImage(R.drawable.navigationbar_back_sel)
                .setLeftOnClickListener(this)
                .setTitleText(isAtWeibo ? "所有微博" : "全部微博")
                .build() ;
    }

    private void initListView() {
        plv_user_info = (Pull2RefreshListView)findViewById(R.id.plv_user_info ) ;
        statusAdapter = new StatusAdapter(this, statuses);
        plv_user_info.setAdapter(statusAdapter);
        plv_user_info.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loadStatuses(1) ;
            }
        });
        plv_user_info.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                loadStatuses( curPage + 1 ) ;
            }
        });
        footView = View.inflate(this,R.layout.footview_loading,null) ;
    }

    private void loadStatuses(final int requestPage) {
        if( !isAtWeibo ){
            statusesAPI.userTimeline(
                    user == null ? -1 : user.getId(),
                    "",
                    0, 0, 5, requestPage, false, 0, false, new RequestListener() {
                        @Override
                        public void onComplete(String response) {
                            if( requestPage == 1 ){
                                statuses.clear();
                            }

                            addStatus(new Gson().fromJson(response,StatusesFriendsTimeline.class)) ;
                        }

                        @Override
                        public void onWeiboException(WeiboException e) {

                        }
                    });
        }else {
            statusesAPI.mentions(
                    0, 0, 50, requestPage, 0,0,0, false, new RequestListener() {
                        @Override
                        public void onComplete(String response) {
                            if( requestPage == 1 ){
                                statuses.clear();
                            }
                            addStatus(new Gson().fromJson(response,StatusesFriendsTimeline.class)) ;
                        }

                        @Override
                        public void onWeiboException(WeiboException e) {

                        }
                    });
        }
    }

    private void addStatus(StatusesFriendsTimeline userTimeline) { //加载数据
        for( Statuses status : userTimeline.getStatuses() ){ //把获取的数据添加到集合中去
            //接口 List<E>containsboolean contains(Object o)如果列表包含指定的元素，则返回 true。
            // 更确切地讲，当且仅当列表包含满足 (o==null ? e==null : o.equals(e)) 的元素 e 时才返回 true。
            if( !statuses.contains(status)){ //list.contains(Bean) ,防止数据的重复添加
                statuses.add(status) ; //数据添加到集合中
            }
        }
        //可能要开线程
        statusAdapter.notifyDataSetChanged();//适配器更新
        plv_user_info.onRefreshComplete();

        if ( curPage < userTimeline.getTotal_number()) { //判断是否继续加载 ,当前页小于总页数
            addFootView(plv_user_info, footView) ; //继续加载
        }else {
            removeFootView(plv_user_info, footView) ; //移除加载
        }
    }

    private void addFootView(PullToRefreshListView plvHome, View footView) {
        ListView lv = plvHome.getRefreshableView();
        if(lv.getFooterViewsCount() == 1) {
            lv.addFooterView(footView);
        }
    }

    private void removeFootView(PullToRefreshListView plvHome, View footView) {
        ListView lv = plvHome.getRefreshableView();
        if(lv.getFooterViewsCount() > 1) {
            lv.removeFooterView(footView);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.titleBarIvLeft :
                finish();
                break;
        }
    }

}
